package swa23.provider.impl;

import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import swa2012.telco.broker.Broker;
import swa2012.telco.broker.beans.BrokerSendMessageStatus;
import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Message;
//import swa2012.telco.broker.beans.Provider;
import swa23.provider.interfaces.ClientProvider;
import swa23.provider.interfaces.ClientRegistry;
import swa23.provider.interfaces.MessageRepository;
//import swa2012.telco.sp.ClientProvider;
//import swa2012.telco.sp.ClientRegistry;
//import swa2012.telco.sp.MessageRepository;
 
	public class ClientProviderImpl implements ClientProvider {
		private static final Logger LOG = LoggerFactory.getLogger(ClientProviderImpl.class);
		private final ClientRegistry clientRegistry;
		private final MessageRepository messageRepository;
		private final TelcoProvider provider;
 
		public ClientProviderImpl(TelcoProvider provider, ClientRegistry clientRegistry, MessageRepository messageRepository) {
			this.provider = provider;
			this.clientRegistry = clientRegistry;
			this.messageRepository = messageRepository;
 
			LOG.info(this + " started up ClientProvider");
		}
 
		public Client register(String clientID) {
			Client client = new Client(clientID, this.provider.getProviderBean());
			LOG.info("Registering client [" + client.getID() + "]: " + client);
			this.clientRegistry.putClient(client);
			return client;
		}
 
		public void deregister(String clientID) {
			LOG.info("Deregistering client [" + clientID + "]");
			this.clientRegistry.removeClient(clientID);
		}
 
		public Collection<Client> listClients() {
			return this.provider.getBroker().listClients();
		}
 
		public Collection<Message> getMessages(String clientID) {
			return this.messageRepository.getMessages(clientID);
		}
 
		public void sendMessage(Message msg) {
			msg.setTimestamp(Long.valueOf(System.currentTimeMillis()));
 
			if (!BrokerUtils.checkMessage(msg)) {
				LOG.info("Message invalid: " + msg);
				return;
			}
 
			if (msg.getReceiver().getProvider().getID().equals(this.provider.getProviderBean().getID())) {
				this.messageRepository.addMessage(msg);
			} else {
				BrokerSendMessageStatus status = this.provider.getBroker().sendMessage(msg);
				LOG.info("Delivered message (via broker): (status=" + status + ") " + msg);
			}
		}
 }
